# *-* coding:utf8 *-*
from datetime import datetime, timedelta
import time

from flask import request, render_template, current_app, g, jsonify
from flask import session,redirect, url_for
from info import user_login_data, constants, db
from info.models import User, News, Category
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import admin_blu

@admin_blu.route('/admin_log')
def admin_log():

    session.pop('is_admin', None)
    return redirect(url_for('admin.admin_login'))


@admin_blu.route('/login',methods = ['GET','POST'])
def admin_login():
    if request.method == 'GET':
        user_id = session.get('user_id',None)
        is_admin = session.get('is_admin',None)
        if user_id and is_admin:
            return redirect(url_for('admin.admin_index'))
        return render_template('admin/login.html')
    # 取参数
    username = request.form.get('username')
    password = request.form.get('password')

    if not all([username,password]):
        return render_template('admin/login.html',errmsg='参数不足')

    try:
        user = User.query.filter(User.mobile == username).first()

    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html',errmsg='数据查询失败')

    if not user:
        return render_template('admin/login.html',errmsg='用户不存在')

    if not user.check_passowrd(password):
        return render_template('admin/login.html',errmsg ='用户密码错误')

    if not user.is_admin:
        return render_template('admin/login.html',errmsg = '用户权限不够')

    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile
    session['is_admin'] = True

    return redirect(url_for('admin.admin_index'))


@admin_blu.route('/index')
@user_login_data
def admin_index():

    user = g.user

    return render_template('admin/index.html',user=user.to_dict())


@admin_blu.route('/user_count')
def user_count():
    '''用户统计'''
    # 查询总人数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()

    except Exception as e:
        current_app.logger.error(e)

    # 查看月新增数
    mon_count = 0
    mon = time.localtime()
    try:
                                #    年　　　　　　　　月
        now_mon = '%d-%02d-01' % (mon.tm_year,mon.tm_mon)
        now_mon_data = datetime.strptime(now_mon,'%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False,User.create_time >= now_mon_data).count()

    except Exception as e:
        current_app.logger.error(e)

    # 查看日新增数
    day_count = 0
    try:
        day_begin = '%d-%02d-%02d' % (mon.tm_year,mon.tm_mon,mon.tm_mday)
        day_begin_data = datetime.strptime(day_begin,'%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False,User.create_time > day_begin_data).count()

    except Exception as e:
        current_app.logger.error(e)

    # 获取当天'年－月－日'时间
    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'),'%Y-%m-%d')

    # 定义空数组，保存数据
    active_date = []
    active_count = []
    count = None

    for i in range(0,31):
        # 添加数据进行反转
        time_end = now_date - timedelta(days = i)
        time_data = now_date - timedelta(days= (i - 1))
        active_date.append(time_end.strftime('%Y-%m-%d'))

        try:
            count = User.query.filter(User.is_admin == False,User.last_login >= time_end,
                                      User.last_login < time_data).count()

        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_count.reverse()
    active_date.reverse()


    data = {"total_count": total_count,
            "mon_count": mon_count,
            "day_count": day_count,
            "active_date": active_date,
            "active_count": active_count}

    return render_template('admin/user_count.html',data = data)

@admin_blu.route('/user_list')
def user_list():
    '''用户列表'''

    page = request.args.get('p',1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    users = []
    current_page = 1
    total_page = 1

    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page,constants.ADMIN_USER_PAGE_MAX_COUNT,False)

        users = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    users_list = list()
    for user in users:
        users_list.append(user.to_admin_dict())


    context = {
        "total_page": total_page,
        "current_page": current_page,
        "users": users_list}

    return render_template('admin/user_list.html',data = context)


@admin_blu.route('/news_review')
def news_review():
    '''返回待审核新闻列表'''
    page = request.args.get('p',1)
    keywords = request.args.get('keywords')

    try:
        page = int(page)

    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1
    try:
        filters = [News.status != 0]
        if keywords:
            filters.append(News.title.contains(keywords))

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = list()
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        'news_list':news_dict_li,
        'total_page':total_page,
        'current_page':current_page
    }
    return render_template('admin/news_review.html',data = data)


@admin_blu.route('/news_review_detail',methods = ["GET","POST"])
def news_review_detail():
    '''新闻审核'''
    if request.method == "GET":
        # 获取新闻id
        news_id = request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_review_detail.html',data = {'errmsg':'为查询到数据'})

        # 通过id查询新闻
        news = None
        try:
            news = News.query.get(news_id)

        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template('admin/news_review_detail.html',data = {'errmsg':'为查询到数据'})

        data = {"news": news.to_dict()}
        return render_template('admin/news_review_detail.html', data=data)

    news_id = request.json.get('news_id')
    action = request.json.get('action')

    if not all([news_id,action]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    if action not in ('accept','reject'):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    news = None
    try:
        news = News.query.get(news_id)

    except Exception as e:
        current_app.logger.error(e)

    if not news:
        jsonify(errno = RET.NODATA,errmsg = '无数据')

    if action == 'accept':
        news.status = 0
    else:
        reason = request.json.get('reason')

        if not reason:
            jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

        news.reason = reason
        news.status = -1

    try:
        db.session.commit()

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '保存失败')

    return jsonify(errno = RET.OK,errmsg = 'OK')


@admin_blu.route('/news_type')
def news_type():

    categoryies = Category.query.all()

    categoryies_dict = []

    for categoes in categoryies:
        cate_dict = categoes.to_dict()

        categoryies_dict.append(cate_dict)

    categoryies_dict.pop(0)

    return render_template('admin/news_type.html',data={"categories": categoryies_dict})



@admin_blu.route('/add_type',methods = ["POST"])
def add_type():

    '''添加或修改'''
    # 取参数json
    add_id = request.json.get('id')
    add_name = request.json.get('name')

    if not add_name:
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    if add_id:
        try:
            category = Category.query.get(add_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.DBERR,errmsg = '查询数据库错误')

        if not category:
            return jsonify(errno = RET.NODATA,errmsg = '无数据')

        category.name = add_name
    else:
        # 如果没有就添加
        cateies = Category()
        cateies.name = add_name
        db.session.add(cateies)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '保存失败')

    return jsonify(errno = RET.OK,errmsg = 'OK')


@admin_blu.route('/news_edit')
def news_edit():

    page = request.args.get('p',1)
    keywords = request.args.get('keywords')

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    total_page = 1
    current_page = 1

    try:
        filters = []
        if keywords:
            filters.append(News.title.contains(keywords))

        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        news_list = paginate.items
        total_page = paginate.page
        current_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    context = {
        "total_page": total_page,
        "current_page": current_page,
        "news_list": news_dict_list}

    return render_template('admin/news_edit.html', data=context)


@admin_blu.route('/news_edit_detail',methods=["GET","POST"])
def news_edit_detail():
    '''新闻版式编辑详情'''
    if request.method == "GET":
        news_id = request.args.get('news_id')

        if not news_id:
            return render_template('admin/news_edit_detail.html',data={"errmsg": "未查询到此新闻"})

        news = None
        try:
            news = News.query.get(news_id)

        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', data={"errmsg": "查询新闻失败"})

        # 查询分类的数据
        categories = Category.query.all()
        categories_li = []
        for category in categories:
            c_dict = category.to_dict()
            c_dict["is_selected"] = False
            if category.id == news.category_id:
                c_dict["is_selected"] = True
            categories_li.append(c_dict)


        data = {"news": news.to_dict(), "categories": categories_li}
        return render_template('admin/news_edit_detail.html', data=data)

    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    if not all([title,digest,content,category_id]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到新闻数据")

    # 1.2 尝试读取图片
    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        # 2. 将标题图片上传到七牛
        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    # 3. 设置相关数据
    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    # 4. 保存到数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="编辑成功")